/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useState } from 'react';
import { ChildLineCommandProps } from './types';

type FormData = {
  start?: pickedVertexData;
  curve?: pickedLineData;
  plane?: pickedFaceData;
  forwardDistance: number;
  backDistance: number;
  angle: number;
};

type Params = {
  mode: 'angle';
  point: string;
  curve: string;
  plane: string;
  forward: number;
  back: number;
  angle: number;
};

export const CurveAngle = ({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) => {
  const initData = {
    forwardDistance: 60,
    backDistance: 0,
    angle: 45,
  };

  const [formData, setFormData] = useState<FormData>(initData);

  const { picker } = useTools();

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const params: Params = props.params;
    const { point, curve, forward, back, plane, angle } = params;

    await initEditDependency([point, curve, plane]);

    setFormData({
      start: picker.generatePickObjByPickID(point) as pickedVertexData,
      curve: picker.generatePickObjByPickID(curve) as pickedLineData,
      plane: picker.generatePickObjByPickID(plane) as pickedFaceData,
      forwardDistance: forward,
      backDistance: back,
      angle,
    });
  }, [editDxid]);

  const isFormDataValid = () => {
    const {
      start: startPoint,
      curve,
      plane,
      forwardDistance,
      backDistance,
    } = formData;

    return (
      startPoint != null &&
      curve != null &&
      plane != null &&
      forwardDistance != null &&
      backDistance != null &&
      forwardDistance !== -backDistance
    );
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) return;

    await execute(false);

    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-line-between-dot', {
      commandName: 'CreateCurve',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    const {
      start: startPoint,
      curve,
      plane,
      forwardDistance,
      backDistance,
      angle,
    } = formData;

    return confirmCommand(
      {
        type: 'Line',
        a: {
          mode: 'angle',
          point: startPoint.vertexId,
          curve: curve.edgeId,
          plane: plane.meshId,
          forward: forwardDistance,
          back: backDistance,
          angle: angle,
        },
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      return;
    }

    await execute(true);
  };

  useAsyncEffect(preview, [formData]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      start: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      curve: {
        type: 'string',
        format: PickInputRJSFFormat.PickCurve,
      },
      plane: {
        type: 'string',
        format: PickInputRJSFFormat.PickPlane,
      },
      forwardDistance: {
        type: 'number',
        title: '向前偏移',
        format: NumberInputFormat.Length,
      },
      backDistance: {
        type: 'number',
        title: '向后偏移',
        format: NumberInputFormat.Length,
      },
      angle: {
        type: 'number',
        title: '角度',
        format: NumberInputFormat.Angle,
      },
    },
  };

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      formData={formData}
      submitLoading={isLoading}
      onChange={(v) => {
        setFormData(v);
      }}
      extraUiSchema={{
        start: {
          'ui:placeholder': '请输入参考点',
          'ui:autofocus': true,
        },
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:options': {
            allowInfiniteLine: true,
          },
        },
        plane: {
          'ui:placeholder': '请输入支持面',
        },
        forwardDistance: {
          'ui:placeholder': '请输入距离',
        },
        backDistance: {
          'ui:placeholder': '请输入距离',
        },
        angle: {
          'ui:placeholder': '请输入角度',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
};
